package com.facedemo.db.utils;

import com.facedemo.MyApplication;
import com.facedemo.db.DaoMaster;
import com.facedemo.db.DaoSession;

import org.greenrobot.greendao.query.QueryBuilder;

public class DaoManager {
    private static final DaoManager ourInstance = new DaoManager();
    private final String DB_Name = "greenDaoTest";
    private DaoMaster daoMaster;
    private DaoMaster.DevOpenHelper devOpenHelper;
    private DaoSession daoSession;

    public static DaoManager getInstance() {
        return ourInstance;
    }

    private DaoManager() {
        devOpenHelper = new DaoMaster.DevOpenHelper(MyApplication.getInstance().getApplicationContext(), DB_Name);
    }

    private DaoMaster getDaoMaster() {
        if (null == daoMaster) {
            daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
        }
        return daoMaster;
    }

    public DaoSession getDaoSession() {
        if (null == daoSession) {
            synchronized (ourInstance) {
                if(null == daoSession) {
                    daoSession = getDaoMaster().newSession();
                }
            }
        }
        return daoSession;
    }

    //设置输出日志，默认关闭
    public void setDebug(boolean b) {
        QueryBuilder.LOG_SQL = b;
        QueryBuilder.LOG_VALUES = b;
    }

    public void closeDaoSession() {
        if (null != daoSession) {
            daoSession.clear();
            daoSession = null;
        }
    }

    public void closeDevOpenHelper() {
        if (null != devOpenHelper) {
            devOpenHelper.close();
            devOpenHelper = null;
        }
    }

    /*
     *   关闭所有的操作 数据库用完的时候必须关闭 节省资源
     */
    public void closeConnection() {
        closeDevOpenHelper();
        closeDaoSession();
    }

}
